<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <el-button v-permission="'add-role'" class="el-button" type="primary" @click="addRole">添加角色</el-button>
      <el-table
        :data="roleList"
        border
      >
        <!-- 放置列 -->
        <el-table-column
          type="index"
          width="50"
          label="序号"
        />
        <el-table-column align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>  {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="onEdit(row)">确定</el-button>
              <el-button type="danger" size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button v-permission="'assign-role'" type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button v-permission="'edit-role'" type="text" size="mini" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" v-permission="'del-role'" type="text" size="mini">删除</el-button>
              </el-popconfirm>
              <!-- 气泡弹层 -->
              <!-- <el-popconfirm title="这是一段内容确定删除吗？" style="margin-left:8px;" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm> -->
            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="center">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="params.pagesize"
          :current-page="params.page"
          :total="total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 弹框组件 -->
    <add-role :visible.sync="showDialog" @updatedepts="getRoleList" />
    <!--分配权限弹框-->
    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <el-tree
        ref="perTreeRef"
        node-key="id"
        :data="permissionData"
        :props="{label:'name'}"
        default-expand-all
        show-checkbox
        check-strictly
        :default-checked-keys="permIds"
      />
      <el-row style="text-align: center;margin-top: 10px;">
        <el-button size="mini" type="primary" @click="btnPermissionOK">确定</el-button>
        <el-button size="mini" type="danger" @click="showPermissionDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>

</template>
<script>
import { getPermissionListApi } from '@/api/permission'
import AddRole from './components/add-role.vue'
import { assignPermApi, delRoleApi, getRoleDetailApi, getRoleListApi, updateRoleApi } from '@/api/role'
import { transListToTreeData } from '@/utils'

export default {
  components: {
    AddRole
  },
  data() {
    return {
      params: {
        page: 1,
        pagesize: 10
      },
      roleList: [],
      total: 0,
      showDialog: false,
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleListApi(this.params)
      // console.log(res)
      this.roleList = res.rows
      this.total = res.total
      // 给数据数组中每一个对象添加一个isEdit属性
      this.roleList.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    changePage(current) {
      this.params.page = current
      this.getRoleList()
    },
    addRole() {
      this.showDialog = true
    },
    btnEditRow(row) {
      // console.log(row)
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async onEdit(row) {
      if (!row.editRow.name || !row.editRow.description) {
        this.$message.warning('角色名称和描述不能为空')
        return
      }
      await updateRoleApi({ ...row.editRow, id: row.id })
      this.$message.success('角色更新成功')
      Object.assign(row, {
        ...row.editRow,
        isEdit: false
      })
    },
    async confirmDel(id) {
      await delRoleApi(id)
      // 最后一页, 最后一条数据
      if (this.roleList.length === 1 && this.params.page > 1) {
        this.params.page -= 1
      }
      this.$message.success('删除角色成功')
      this.getRoleList()
    },
    async btnPermission(id) {
      this.permissionData = transListToTreeData(await getPermissionListApi(id), 0)
      this.currentRoleId = id
      const { permIds } = await getRoleDetailApi(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPermApi({
        id: this.currentRoleId,
        permIds: this.$refs.perTreeRef.getCheckedKeys()
      })
      this.$message.success('权限分配成功')
      this.showPermissionDialog = false
    }

  }
}
</script>
<style scoped lang="scss">
.el-button{
  margin: 20px;
}
.app-container{
  padding: 20px;
}
</style>
